﻿using FNN.CustomFunctions;
using FNN.NetworkMasters;
using FNN.Networks;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using FNN.Factories.Helpers;
using FNN.Helpers.IO;
using FNN.Factories.Networks;

namespace GraphicFNN.Pages
{
    /// <summary>
    /// Логика взаимодействия для CultivationPage.xaml
    /// </summary>
    public partial class CultivationPage : Page
    {
        public CultivationPage()
        {
            InitializeComponent();
        }

        private void BtnCultivate_OnClick(object sender, RoutedEventArgs e)
        {
            var helper = DataSourceHelperFactory.CreateHelper((NetworkTypes)CmbType.SelectedIndex, TxtSourcePath.Text);
            var masterFactory = new NetworkMasterFactory(helper);

            var chartWindow = new ChartWindow();
            NetworkMaster netMaster = masterFactory.CreateMaster((NetworkTypes)CmbType.SelectedIndex);
            Network targetNetwork = NetworkFactory.CreateNetwork((NetworkTypes)CmbType.SelectedIndex, 
                new FNN.Options.NetworkOptions(Convert.ToInt32(TxtInputCount.Text), Convert.ToInt32(TxtLayerCount.Text),
                            Convert.ToInt32(TxtLayerNeuronCount.Text),
                            new List<FunctionTypes> { (FunctionTypes)(CmbFunctions.SelectedIndex - 1) },
                            Convert.ToInt32(TxtOutputCount.Text)));

            netMaster.GenerationChanged += chartWindow.CatchIterationChanged;
            netMaster.GenerationResultsImproved += chartWindow.CatchResultsImproved;

            if (netMaster == null) return;
            netMaster.IterationsLimit = 1000;
            netMaster.GeneticIterationsLimit = 1000;
            chartWindow.Show();
            var backgroundTask = Task.Factory.StartNew(() =>
            {
                var serializationHelper = new SerializationHelper();
                var targetName = "";
                Dispatcher.Invoke(() =>
                {
                    targetName = TxtNetworkName.Text;
                    var resultNetwork = netMaster.NetworkCultivation(targetNetwork, true);
                    serializationHelper.WriteBinary(resultNetwork, targetName + ".fnn");
                });
            });
        }

        private void BtnSelectSource_OnClick(object sender, RoutedEventArgs e)
        {
            var fileBrowser = new OpenFileDialog
            {
                CheckFileExists = true,
                Multiselect = false,
                Filter = "CSV|*.csv"
            };
            fileBrowser.ShowDialog();
            TxtSourcePath.Text = fileBrowser.FileName;
        }
    }
}
